import { NextResponse } from 'next/server'
import prisma from '@/lib/db'
import {verifyToken} from '@/lib/auth'


export async function GET(request: Request): Promise<Response> {
    try {
      const token = request.headers.get('Authorization')?.split(' ')[1]
      const payload = token ? verifyToken(token) : null;
    
      if (!payload) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
      }

      // 获取 product_id 参数
      const url = new URL(request.url);
      const product_id = url.searchParams.get('product_id');
      
      if (!product_id) {
        return NextResponse.json({ error: 'Missing product_id parameter' }, { status: 400 });
      }
  
      const topics = await prisma.productTopic.findMany({
        where: {
          product_id:product_id
        },
        orderBy: {
          pxh: 'asc'
        },
        select: {
            id: true,
            name: true,
            pxh: true,
            copies: {
              orderBy: {
                pxh: 'asc'
              },
              select: {
                id: true,
                title: true,
                pxh: true,
                topic_id: true
              }
            }
        }
      })
      
      
      return new Response(JSON.stringify(topics), {
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (error: any) {
      return new Response(JSON.stringify({ error: error.message || '获取话题失败' }), {
        status: 500,
        headers: {
          'Content-Type': 'application/json'
        }
      })
    }
  }